package com.earl.mbasystem.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.StrutsStatics;

import com.earl.mbasystem.security.shiro.ShiroPrincipal;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 权限控制拦截器.
 * 用户必须登录系统才能够进行其他基本操作.
 * @author 黄祥谦.
 */
public class ShiroInterceptor extends AbstractInterceptor {

	/**
     * 
     */
	private static final long serialVersionUID = 1L;

	/**
	 * log4j实例对象.
	 */
	private static Logger logger = LogManager.getLogger(ShiroInterceptor.class
			.getName());

	@Override
	public final String intercept(final ActionInvocation invocation)
			throws Exception {
		logger.debug("进入权限拦截器");
		// 获取参数
		ActionContext ctx = invocation.getInvocationContext();
		// 获取HttpServletRequest
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(StrutsStatics.HTTP_REQUEST);
		String path = request.getServletPath();
		
		Subject subject = SecurityUtils.getSubject();  
		
		if(subject.isAuthenticated()){
			ShiroPrincipal user= (ShiroPrincipal) subject.getPrincipal();
			
			List<String> authorities = user.getAuthorities();//权限url
			if(authorities.contains(path)){
				invocation.invoke();
			}else{
				logger.info("【"+user.getUsername()+"】"+"没有权限访问 "+path +" 的权限");
			}
		}else{
			//要登陆的地址
			if("/user_dologin.action".equals(path)){
				invocation.invoke();
			}else{

			logger.info("未登录系统，没有任何操作权限");

				}
		}
		
		logger.debug("退出权限拦截器");
		return null;
	}
}
